package com.hexb.core.common

import com.fasterxml.jackson.annotation.JsonInclude
import com.hexb.core.exception.BusinessException

/**
 * restful接口数据返回结构
 * @field data
 * @field code
 * @field message
 * */
@JsonInclude(JsonInclude.Include.NON_NULL)
class ResponseResult<T> {

    final static int STATUS_FAILURE = 0
    final static int STATUS_SUCCESS = 1

    final static String OK = 'OK'

    T data
    int status = STATUS_SUCCESS
    String code
    String message

    ResponseResult() {
    }

    private ResponseResult(T data, String code, String message) {
        this.data = data
        this.code = code
        this.message = message
    }

    private ResponseResult(BusinessException e) {
        this.code = e.code
        this.message = e.message
        this.status = STATUS_FAILURE
    }
    
    /**
     * 构建正常结果
     * */
    static <T> ResponseResult successful(T data, String code = OK, String message = "操作成功") {
        new ResponseResult(data, code, message)
    }

    /**
     * 构建异常结果
     * */
    static ResponseResult unsuccessful(BusinessException e) {
        new ResponseResult(e)
    }

    /**
     * 构建异常结果
     * */
    static ResponseResult unsuccessful(Exception e, String code = "unknown_exception", String message = "服务调用异常") {
        def result = new ResponseResult(e, code, message)
        result.status = STATUS_FAILURE
        result
    }

    /**
     * 构建异常结果
     * */
    static ResponseResult unsuccessful(String code = "unknown_exception", String message = "服务调用异常") {
        def result = new ResponseResult(null, code, message)
        result.status = STATUS_FAILURE
        result
    }

}
